package com.whats.indicator.service.di;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONArray;
import com.whats.indicator.entity.EquipAssetst;
import com.whats.indicator.service.MppEquipAssetstService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

@Service
public class EquipAssetstDiService implements ApplicationRunner {

    @Value("${outter.data.equip-assetst-url}")
    private String equipAssetstUrl;

    private static final int SYNC_PERIOD = 5;
    private static final int PAGESIZE = 1000;

    private static final Logger LOGGER = LoggerFactory.getLogger(EquipAssetstDiService.class);
    private static final String APP_CODE = "0bb3c141c4c34aaf925c49e4ccac6435";
    @Autowired
    private MppEquipAssetstService mppEquipAssetstService;
    public void acquireData() {
        LOGGER.info("===============begin acquireData url {}", equipAssetstUrl);

        int pageNum = 1;
        // 请求参数
        equipAssetstUrl += "?appCode=" + APP_CODE + "&pageSize=" + PAGESIZE;
        LocalDateTime currDateTime = LocalDateTime.now();
        while(true) {
            String url =equipAssetstUrl + "&pageNum=" + pageNum + "&ctimeS=" + currDateTime.minusDays(SYNC_PERIOD).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            url += "&ctimeE=" + currDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            // 发送POST请求
            String response = HttpUtil.createPost(url)
                    .form(MapUtil.of("key", "value"))
                    .timeout(20000)
                    .execute() // 执行请求
                    .body();

            if (StrUtil.isEmpty(response)) {
                LOGGER.error("======EquipAssetstDi acquireData err");
                break;
            }
            JSONObject resultData = JSONUtil.parseObj(response);
            LOGGER.info("======EquipAssetstDi acquireData response code {}, pageNum {}", resultData.getInt("errCode"), pageNum);
            boolean isBreak = true;
            int resultDataSize = 0;
            if (Integer.valueOf(0).equals(resultData.getInt("errCode")) && resultData.getJSONObject("data") != null) {
                cn.hutool.json.JSONArray rows = resultData.getJSONObject("data").getJSONArray("rows");
                if (!rows.isEmpty()) {
                    if (rows.size() > 0) {
                        resultDataSize = rows.size();
                        isBreak = false;
                    }
                    List<EquipAssetst> equipAssetstList = JSONArray.parseArray(rows.toString(), EquipAssetst.class);
                    mppEquipAssetstService.saveEquipAssetst(equipAssetstList);
                }
            }
            if (isBreak) {
                break;
            }
            if (resultDataSize < PAGESIZE) {
                pageNum = 0;
                currDateTime = currDateTime.minusDays(SYNC_PERIOD);
            }
            pageNum++;
        }
    }

    @Override
    public void run(ApplicationArguments args) {
        try {
            acquireData();
        }catch (Exception e) {
            LOGGER.error("==========run acquireData err");
        }
    }

    public static void main(String[] args) {
//        System.out.println(LocalDateTime.now());
    }
}
